using System;
using System.Collections;
using System.Collections.Generic;
using EventUtils;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using View;
using ZWFrameWork;

public class HeadsManager : SingletonInstance<HeadsManager>
{
    private int mAllHeadCount = 8;
    private Dictionary<int, Texture> mHeadInfoUpLoadDic = new Dictionary<int, Texture>();
    private Dictionary<int, Texture> mHeadInfoNormalDic = new Dictionary<int, Texture>();

    public void OnLoadSelfHead(RawImage tex,uint customid_,int faceid)
    {
        string localpath = OnGetLoadHeadKey(1);
        if (localpath == "")
        {
            OnLoadHead(tex, customid_, faceid);
        }
        else
        {
            Utils.StartCoroutine(_OnLoadHeadForUrl(localpath, tex, (int)customid_,false));
        }
    }
    
    public void OnLoadHead(RawImage tex,uint customid_,int faceid)
    {
        int customid = (int)customid_;
        if (customid != null && customid >= 1)
        {
            Utils.StartCoroutine(_OnLoadHeadForUrl(OnMatchingHeadLoadUrl(customid), tex, customid));
        }
        else
        {
            if (faceid >= mAllHeadCount)
            {
                faceid = mAllHeadCount-1;
            }

            int newfaceid = faceid + 1;
            if (mHeadInfoNormalDic.ContainsKey(newfaceid))
            {
                tex.texture = mHeadInfoNormalDic[newfaceid];
            }
            else
            {
                Action ac = () =>
                {
                    Texture texture = UIManager.Instance.LoadTexture("hall/textures/Common/head", "img_" + newfaceid);
                    tex.texture = texture;
                    if (mHeadInfoNormalDic.ContainsKey(newfaceid))
                    {
                        mHeadInfoNormalDic.Add(newfaceid, texture);
                    }
                };
                ac();
            }
        }
    }

    //加载一张头像
    [Obsolete("Obsolete")]
    IEnumerator _OnLoadHeadForUrl(string path_,RawImage tex,int customid,bool isup=false)
    {
        int customlocalid = customid;
        if (mHeadInfoUpLoadDic.ContainsKey(customlocalid) && customlocalid > 0)
        {
            tex.texture = mHeadInfoUpLoadDic[customlocalid];
            yield break;
        }

        string path = "";
        if (isup)
            path = string.Format("file://{0}",path_);
        else
            path = path_;
        Debug.Log("加载的路径："+path);
        
        WWW www = new WWW(path);
        yield return www;
        if (www.error != null)
        {
            Debug.LogError(string.Format("Load head error {0}",www.error));
        }
        else
        {
            if (tex != null)
            {
                tex.texture = www.texture;
            }

            if (!mHeadInfoUpLoadDic.ContainsKey(customlocalid))
            {
                mHeadInfoUpLoadDic.Add(customlocalid, www.texture);
            }
            
            if (isup)
            {
                //s上传一张头像
                WWWForm form = new WWWForm();
                form.AddField("userId", (int)GlobalUserItem.dwUserID);
                form.AddField("type", 1);
                form.AddBinaryData("avatar", www.bytes);
                //上传
                using (UnityWebRequest request = UnityWebRequest.Post("/user/uploadAvatar", form))
                {
                    yield return request.SendWebRequest();
                    if (request.isNetworkError || request.isHttpError)
                    {
                        Debug.LogError("上传失败");
                    }
                    else
                    {
                        string text = request.downloadHandler.text;
                        Debug.Log("服务器返回值"+text);
                    }
                }
                PlayerPrefs.SetInt(GlobalUserItem.LocalUpHeadTimeKey,DateTime.Now.Day);
            }
        }
    }
    
    //获取头像的Url
    string OnMatchingHeadLoadUrl(int customid)
    {
        string url = "";

        if (customid != null && customid > 0)
        {
                url = string.Format("https://cooltrade.s3.ap-south-1.amazonaws.com/{0}.jpg", customid);
        }
        return url;
    }


    private string mOnUpLoadHeadKey = "Load_Up_Head_Key_";
    private string mOnUpLoadLocalHeadKey = "Local_Local_Up_Head_Key_";

    /// <summary>
    /// 上传的时候本地保存的图
    /// </summary>
    /// <param name="type"> 1取  2设置 3删除</param>
    /// <param name="localpath"></param>
    /// <returns></returns>
    public string OnGetLoadHeadKey(int type,string localpath = "")
    {
        string key = mOnUpLoadHeadKey + GlobalUserItem.dwUserID;
        string path = "";
        if (type == 1)
        {
            if (PlayerPrefs.HasKey(key))
            {
                path = PlayerPrefs.GetString(key);
            }
            return path;
        }
        else if (type == 2)
        {
            PlayerPrefs.SetString(key,localpath);
            path = localpath;
            Utils.StartCoroutine(_OnLoadHeadForUrl(localpath, null, -1,true));
        }
        else if (type == 3)
        {
            PlayerPrefs.DeleteKey(key);
        }
        return "";
    }
    //保存一下上传的时候的图的地址
    public string OnSetLoadLoadlHeadKey(string localpath,bool isget=false)
    {
        string key = mOnUpLoadLocalHeadKey + GlobalUserItem.dwUserID;
        string path = "";
        if (isget)
        {
            if (PlayerPrefs.HasKey(key))
            {
                path = PlayerPrefs.GetString(key);
            }
            else
            {
                path = "";
            }
        }
        else
        {
            PlayerPrefs.SetString(key,localpath);
            path = localpath;
        }
        return path;
    }

    public void OnEnterLoadHead(string path)
    {
        OnGetLoadHeadKey(2, path);
    }
    
    
    /// <summary>
    /// 初始化数据
    /// </summary>
    public override void InitData()
    {
        mHeadInfoUpLoadDic = new Dictionary<int, Texture>();
        mHeadInfoNormalDic = new Dictionary<int, Texture>();
    }

    /// <summary>
    /// 清理数据
    /// </summary>
    public override void ClearData()
    {
        mHeadInfoUpLoadDic = new Dictionary<int, Texture>();
        mHeadInfoNormalDic = new Dictionary<int, Texture>();
    }
}
